<template>
  <split splitHeight="calc(100vh-5px)" leftWidth="240" style="margin-top: 4px; overflow: hidden">
    <template #paneL>
      <CustomerTree @onClick="onClick"/>
      <div style="border: 1px #F0F0F0 solid; height: 217px; padding: 10px; margin-top: 5px;">
        <ul>
          <li v-for="(item, index) in summaryData" :key="item.id">
            <span class="text-red-500 mr-10px">{{ item.itemValue }}</span>
            <span class="mb-10px">{{ item.itemText }}</span>
            <span style="float: right;">{{ item.cn }}</span>
          </li>
        </ul>
      </div>
    </template>
    <template #paneR>
      <div>
        <!--引用表格-->
        <BasicTable @register="registerTable" :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" :loading="loading">
          <!--插槽:table标题-->
          <template #tableTitle>
            <a-button type="primary" color="success" preIcon="ant-design:plus-outlined" @click="handleAdd" > 新增</a-button>
            <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleEdit" :disabled="disabled"> 编辑 </a-button>
            <a-button type="primary" color="error" preIcon="ant-design:clear-outlined" @click="handleDelete" :disabled="disabled"> 删除 </a-button>
            <!--a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button-->
            <j-upload-button type="primary" color="warning" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
            <a-button type="primary" color="error" @click="handleBatchEdit()" v-auth="'policy:update-batch'" :disabled="!updateParam.beginDate || dataSource.length == 0 || updateParam.cId.length <= 0">批量更新</a-button>
            <a-button type="primary" @click="createMonth()" v-auth="'policy:create-month'" :disabled="!queryParam.beginDate || dataSource.length == 0">复制到下月</a-button>
            <span class="ml-15 leading-32px h-32px">有效日期:</span>
            <a-date-picker
              v-model:value="queryParam.beginDate"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 125px; "
            /> ~
            <a-date-picker
              v-model:value="queryParam.endDate"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 125px"
            />
            <a-button type="primary" color="success" @click="preBtnQuery()" >上月</a-button>
            <a-button type="primary" color="success" @click="nexBtnQuery()" >下月</a-button>
            <a-button type="primary" color="success" @click="curBtnQuery()" >本月</a-button>
            <a-button type="primary" @click="searchQuery()" >查询</a-button>
          </template>
        </BasicTable>

        <!-- 表单区域 {{ queryParam }} {{ !queryParam.customerId }} -->
        <PolicyModal @register="registerModal" @success="handleSuccess"></PolicyModal>

        <!-- 批量修改 -->
        <PolicyBatch @register="registerBatch" @success="handleSuccess"></PolicyBatch>
      </div>
    </template>
  </split>  
</template>

<script lang="ts" name="policy-list" setup>
import { ref, computed, unref, toRaw, reactive, nextTick } from 'vue';
import { BasicTable } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns } from './Policy.data';
import { deleteOne, getImportUrl, getExportUrl, updateBatchOrders, createMonthData } from './Policy.api';
import { defHttp } from "/@/utils/http/axios";
import { filterObj } from "/@/utils/common/compUtils";

import CustomerTree from "./CustomerTree.vue"
import PolicyModal from './modules/PolicyModal.vue';
import PolicyBatch from './modules/PolicyBatch.vue';
import Split from '/@/components/pt/split/Index.vue'
import moment from 'dayjs'

//初始化 -------------------------------------------------------------
const expandedRowKeys = ref<string[]>(['1790227530305888272366.99']);

//定义查询表单，查询条件 policyType: '', timeLimit: '',
const queryParam = reactive<any>({
  parentId: '',
  beginDate: moment().subtract( 0, 'months').format('YYYY-MM-01'),
  endDate: moment().add( 0, 'months').endOf('month').format('YYYY-MM-DD'),
});

//批量更新参数
const updateParam = reactive<any>({
  beginDate: queryParam.beginDate,
  endDate: queryParam.endDate,
  cId: '',
  timeLimit: '',
  rate: '',
  policyType: ''
});

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate;
  if (!beginDate || !endDate) {
    return false;
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate;
  if (!endDate || !beginDate) {
    return false;
  }
  return moment(beginDate).valueOf() > endDate.valueOf();
}
//初始化 -------------------------------------------------------------

const disabled = ref(true);
const options  = ref([]);
const index    = ref(0);

//注册model
const [registerModal, { openModal : openModal }] = useModal();
const [registerBatch, { openModal : openBatch }] = useModal();
//注册table数据
const loading = ref<boolean>(false);
const dataSource = ref<any[]>([]);
const summaryData = ref<any[]>([]);
const { tableContext, onImportXls } = useListPage({
  tableProps: {
    rowKey: "id",
    size: "small",
    dataSource: dataSource,
    columns: columns,
    pagination: false,
    isTreeTable: true,
    striped: true,
    useSearchForm: false,
    bordered: true,
    showTableSetting: false,
    showActionColumn: false,
    resizeHeightOffset: 40,
    expandedRowKeys: expandedRowKeys,
    showSummary: true,
    onExpand: onExpand,
  },
  exportConfig: {
    url: getExportUrl,
    name: '填值规则列表',
  },
  importConfig: {
    url: getImportUrl,
    success: () => searchQuery(),
  },
});

//注册table数据
const [registerTable, { reload, collapseAll }] = tableContext;
const url = '/policy/policy/treeGrid';
async function loadData(params) {
  loading.value = true;
  let result = await defHttp.get({ url, params });
  loading.value = false;
  return result;
}

/** 点击展开图标时触发 */
async function onExpand(isExpand, rowData) {
  if (isExpand && rowData.hasChildren === "true" && rowData.children.length === 0) {
    let params = { 
      parentId: rowData.customerId, 
      type: rowData.type 
    }
    if (rowData.type == '1') {
      params['timeLimit'] = rowData.timeLimit
    } else if (rowData.type == '2') {
      params['timeLimit'] = rowData.timeLimit
      params['rate'] = rowData.rate
    }
    Object.assign(params, queryParam);
    const res = await loadData(filterObj(params));
    rowData.children = res.rows;
  }
}

async function loadRootData() {
  const res = await loadData(filterObj(queryParam));
  if (res) {
    dataSource.value = res.rows;
    summaryData.value = res.footer;
  } else {
    dataSource.value = [];
    summaryData.value = [];
  }
}

function searchQuery() {
  nextTick(collapseAll);
  loadRootData();
}

// 上月
function preBtnQuery() {
  ++index.value
  queryParam.beginDate = moment().subtract( index.value, 'months').format('YYYY-MM-01')
  queryParam.endDate = moment().subtract( index.value, 'months').endOf('month').format('YYYY-MM-DD')
  searchQuery()
}

// 下月
function nexBtnQuery() {
  --index.value
  queryParam.beginDate = moment().subtract( index.value, 'months').format('YYYY-MM-01')
  queryParam.endDate = moment().subtract( index.value, 'months').endOf('month').format('YYYY-MM-DD')
  searchQuery()
}

// 本月-
function curBtnQuery() {
  index.value = 0
  queryParam.beginDate = moment().subtract( index.value, 'months').format('YYYY-MM-01')
  queryParam.endDate = moment().subtract( index.value, 'months').endOf('month').format('YYYY-MM-DD')
  searchQuery()
}

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 编辑事件
 */
function handleEdit() {
  if (disabled.value == true) {
    return
  }
  let record = { id: selectRows.id };
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}

/**
 * 编辑事件
 */
function handleBatchEdit() {
  // const customerId = queryParam.customerId && queryParam.customerId.split(",")
  // const arrays = customerId <= 0 ? [] : customerId.filter(item => item) //[366,381,382]//e
  let record = reactive<any>({});
  updateParam.beginDate = queryParam.beginDate;
  updateParam.endDate = queryParam.endDate;
  Object.assign(record, updateParam);

  openBatch(true, {
    record,
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 删除事件
 */
async function handleDelete() {
  if (!selectRows.id) {
    return
  }
  await deleteOne({ id: selectRows.id }, reload);
}

/**
 * 更新排序
 */
async function createMonth() {
  var date = queryParam.beginDate;
  if (!date) {
    return false;
  }
  await createMonthData({date: date});
}

/**
 * 成功回调
 */
function handleSuccess() {
  searchQuery();
}

//单击行
let selectRows = reactive<any>({id: '', type: ''});
function handleClick(record) {
  selectRows.id = record.id
  selectRows.type = record.type
  if (record.type == '3') {
    disabled.value = false
  } else {
    disabled.value = true
  }

  //批量修改
  if (record.path) {
    updateParam.cId = record.path.split(",").filter(item => item);
  } else {
    updateParam.cId = [];
  }
  updateParam.timeLimit = record.timeLimit;
  if (record.type == '1') {
    updateParam.rate = "";
    updateParam.policyType = "";
  } else if (record.type == '2') {
    updateParam.rate = record.rate;
    updateParam.policyType = "";
  } else if (record.type == '3') {
    updateParam.rate = record.rate;
    updateParam.policyType = record.policyType;
  }
  //console.info("updateParam@@@@", updateParam);
}

//双击行
function handleDblclick() {
  handleEdit();
}

//选择行
function rowClassName(record, index) {
  return record.id === selectRows.id ? 'row-selected' : '';
}

/**
 * 树节点点击事件
 * 当点城市 type = 0, 加1后 customer.type = 1 公司
 * @param treeNode
 * @returns {boolean}
 */
 function onClick(treeNode) {
  var id = treeNode.path;
  if (id && queryParam.customerId != id) {
    queryParam.customerId  = id;
    updateParam.cId = id.split(",").filter(item => item);
  } else {
    queryParam.customerId  = '';
    updateParam.cId = [];
  }
  updateParam.timeLimit = '';
  updateParam.rate = '';
  updateParam.policyType = '';
  console.info("updateParam@@@@", updateParam);
  searchQuery();
}

//默认执行查询
searchQuery();

</script>
<style scoped>
  span:not(:last-child) {
    margin-right: 4px;
  }
</style>